<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert
        show-icon
        :closable="false"
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
      >
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col
          ><span>选择商品分类：</span>
          <!-- 选择商品分类的级联选择框 -->
          <!-- 级联选择器 -->
          <!-- options用来指定数据源 -->
          <!-- props用来指定配置对象 -->
          <el-cascader
            v-model="selectedKeys"
            :options="cateList"
            :props="casCaderProps"
            @change="cateChange"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 添加动态参数的面板 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加参数的按钮 -->
          <el-button
            type="primary"
            size="mini"
            :disabled="isBitDisabled"
            @click="addParamsDialog"
            >添加参数</el-button
          >
          <el-table :data="manyTableData" stripe border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index,scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 切换显示button按钮和输入框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              :label="titleText + '名称'"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editParamsDialog(scope.row.attr_id)"
                  >修改</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParamsDialog(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性的面版 -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加属性的按钮  -->
          <el-button
            type="primary"
            size="mini"
            :disabled="isBitDisabled"
            @click="addParamsDialog"
            >添加属性</el-button
          >
          <el-table :data="onlyTableData" stripe border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index,scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 切换显示button按钮和输入框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              :label="titleText + '名称'"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editParamsDialog(scope.row.attr_id)"
                  >修改</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParamsDialog(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addParamsDialogVisible"
      width="50%"
      @close="closeAddParamsDialog"
    >
      <!-- 添加参数表单 -->
      <el-form
        :model="addParamsForm"
        ref="addParamsRef"
        label-width="100px"
        :rules="addParamsRule"
      >
        <el-form-item :label="titleText + '名称'" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams(paramsId)">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑参数对话框 -->
    <el-dialog
      :title="'编辑' + titleText"
      :visible.sync="editParamsDialogVisible"
      width="50%"
      @close="closeEditParamsDialog"
    >
      <!-- 编辑参数表单 -->
      <el-form
        :model="editParamsForm"
        ref="editParamsRef"
        label-width="100px"
        :rules="editParamsRule"
      >
        <el-form-item :label="titleText + '名称'" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams(paramsId)"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //商品分类的数据列表，默认为空
      cateList: [],
      //指定配置对象
      casCaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover',
        checkStrictly: true,
      },
      //选中父级分类的id数组
      selectedKeys: [],
      //   被激活的页签名称
      activeName: 'many',
      //动态参数列表数据
      manyTableData: [],
      //静态参数列表数据
      onlyTableData: [],
      //添加参数对话框
      addParamsDialogVisible: false,
      //添加参数的表单数据
      addParamsForm: {
        //将要添加分类的名称
        attr_name: '',
      },
      // 添加分类表单规则
      addParamsRule: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },
      //编辑参数对话框
      editParamsDialogVisible: false,
      //编辑参数的表单数据
      editParamsForm: {
        //将要添加分类的名称
        attr_name: '',
      },
      // 编辑分类表单规则
      editParamsRule: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },
      //表格参数id
      paramsId: '',
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    //获取商品分类的数据
    async getCateList() {
      const { data: res } = await this.$https.get('/categories')
      if (res.meta.status != 200) {
        this.$message.error('分类列表获取失败！')
      }
      this.cateList = res.data
    },
    //选择项目发生变化触发这个函数
    cateChange() {
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      //根据选择三级id和切换参数类型获取参数
      this.getParamsData()
    },
    //tab页签点击事件的处理函数
    handleTabClick() {
      // 每次切换获取参数
      this.getParamsData()
    },
    //根据选择三级id和切换参数类型获取参数
    async getParamsData() {
      const { data: res } = await this.$https.get(
        `categories/${this.thirdId}/attributes`,
        {
          params: {
            sel: this.activeName,
          },
        }
      )
      if (res.meta.status != 200) {
        this.$message.error('参数列表获取失败！')
      }
      //遍历数组将字符串转为数组,如果为空字符串返回空数据
      res.data.forEach((items) => {
        items.attr_vals = items.attr_vals ? items.attr_vals.split(' ') : []
       //tag标签输入框的显示和隐藏
       items.inputVisible = false
      //绑定tag标签输入框的值
        items.inputValue = ''
      })
      //判断切换的状态是动态参数还是静态参数
      if (this.activeName === 'many') {
        this.manyTableData = res.data
        console.log(this.manyTableData)
      }
      this.onlyTableData = res.data
    },
    //添加参数对话框
    addParamsDialog() {
      this.addParamsDialogVisible = true
    },
    //关闭添加参数对话框
    closeAddParamsDialog() {
      this.$refs.addParamsRef.resetFields()
    },
    //添加参数
    addParams() {
      //表单预验证
      this.$refs.addParamsRef.validate(async (valid) => {
        if (!valid) return
        //可以发起添加参数请求
        const { data: res } = await this.$https.post(
          `categories/${this.thirdId}/attributes`,
          {
            attr_name: this.addParamsForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        if (res.meta.status != 201) {
          return this.$message.error('添加' + this.titleText + '失败！')
        }
        this.$message.success('添加' + this.titleText + '成功！')
        //关闭添加参数对话框
        this.addParamsDialogVisible = false
        //刷新页面
        this.getParamsData()
      })
    },
    // 编辑参数对话框
    async editParamsDialog(id) {
      this.paramsId = id
      this.editParamsDialogVisible = true
      const { data: res } = await this.$https.get(
        `categories/${this.thirdId}/attributes/${id}`,
        { params: { attr_sel: this.activeName } }
      )
      if (res.meta.status != 200) {
        this.$message.error('查询参数失败！')
      }
      this.editParamsForm.attr_name = res.data.attr_name
    },
    //关闭编辑参数对话框
    closeEditParamsDialog() {
      this.$refs.editParamsRef.resetFields()
    },
    //添加参数
    editParams(id) {
      //表单预验证
      this.$refs.editParamsRef.validate(async (valid) => {
        if (!valid) return
        //可以发起修改参数请求
        const { data: res } = await this.$https.put(
          `categories/${this.thirdId}/attributes/${id}`,
          {
            attr_name: this.editParamsForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        if (res.meta.status != 200) {
          return this.$message.error('修改' + this.titleText + '失败！')
        }
        this.$message.success('修改' + this.titleText + '成功！')
        //关闭添加参数对话框
        this.editParamsDialogVisible = false
        //刷新页面
        this.getParamsData()
      })
    },
    async removeParamsDialog(id) {
      const resResult = await this.$confirm(
        `此操作将永久删除该${this.titleText}, 是否继续?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((error) => error)
      if (resResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$https.delete(
        `categories/${this.thirdId}/attributes/${id}`
      )
      if (res.meta.status != 200) {
        return this.$message.error('删除失败！')
      }
      this.$message.success('删除成功！')
      this.getParamsData()
    },
    //tag标签输入框失去焦点，回车触发此函数
    handleInputConfirm(row) {
      //输入框如果有空格字符串就清空
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      //后续操作
      row.attr_vals.push(row.inputValue.trim())
      row.inputVisible = false
      row.inputValue = ''
      //发起请求
      this.getTagParams(row)
    },
    // 发起编辑和删除tag标签的请求
    async getTagParams(row) {
      const {data:res} = await this.$https.put(`categories/${this.thirdId}/attributes/${row.attr_id}`,{
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status != 200) {
        return this.$message.error('修改参数项失败！')
      }
    },
    // tag标签点击按钮触发此函数
    showInput(row) {
      row.inputVisible = true
      //文本框自动获取焦点
       this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
    },
    //删除tag标签
    handleClose(index,row) {
      row.attr_vals.splice(index,1)
      this.getTagParams(row)
    }
  },
  computed: {
    //判段添加参数和添加属性按钮是否应该被禁用
    isBitDisabled() {
      if (this.selectedKeys.length !== 3) {
        return true
      }
      return false
    },
    //拿到三级id
    thirdId() {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      }
      return null
    },
    //添加参数标题文本
    titleText() {
      if (this.activeName === 'many') {
        return '参数'
      }
      return '属性'
    },
  },
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.el-tag {
  margin: 0 10px;
}
.input-new-tag {
  width: 120px;
}
</style>
